package com.asia5b.a5mall.middleware.config

import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.middleware.api.ApiManager
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.model.member.AccessTokenModel
import com.asia5b.a5mall.middleware.model.order.OrderPayModel
import com.asia5b.a5mall.middleware.api.CustomThrowable
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.utils.Preference
import com.google.gson.reflect.TypeToken
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * Created by zhangyuncai on 2020/3/31.
 */
/**
 * 跳转武时亿支付之前判断登录token是否存在,否则先获取
 */
object Asia5bPayUtils {

    //LibPay_Authorization,这个key和支付模块中的key一模一样
    var AuthorizationKey = "LibPay_Authorization"
    var AuthorizationValue by Preference<String>(AuthorizationKey,"")

    fun getAuthorization(activity: SimpleActivity<*,*>, isBindPay: Boolean = false, callback: (canSkip: Boolean) -> Unit) {
        if (!TextUtils.isEmpty(AuthorizationValue)) {
            callback.invoke(true)
        } else {
            val orderApi = ApiManager.API_ORDER
            orderApi.getPayToken()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe {
                        activity.showLoadingBar("")
                    }
                    .doAfterTerminate {
                        activity.dismissLoadingBar()
                    }
                    .subscribe(Consumer {
                        if (it.isSuccess) {
                            val type = object : TypeToken<AccessTokenModel>() {}.type
                            JsonUtil.jsonToAny<AccessTokenModel>(JsonUtil.anyToJson(it.data!!), type)?.let { accessTokenModel ->
                                if (!TextUtils.isEmpty(accessTokenModel.accessToken)) {
                                    AuthorizationValue = accessTokenModel.accessToken
                                    callback.invoke(true)
                                }
                            }
                        } else {
                            showMessage(it.message)
                            callback.invoke(false)
                        }
                    }, Consumer {
                        it.printStackTrace()
                        callback.invoke(false)
                    }).joinComposite(activity.mCompositeDisposable)
        }


    }

    /**
     * 跳转到武时亿充值页面
     */
    fun skipPayTopup(activity: SimpleActivity<*,*>) {
        getAuthorization(activity, true) { canSkip ->
            if (canSkip) {
                activity.push("/pay/paycharge", {
                    it.withInt("type", 0)
                })
            }
        }
    }

    /**
     * 跳转到武时亿支付页面
     */
    fun skipPay(activity: SimpleActivity<*,*>, pay: OrderPayModel, callback: ((Boolean)->Unit)?=null) {
        getAuthorization(activity) { canSkip ->
            if (canSkip) {
                activity.push("/pay/paycharge", {
                    it.withString("pay_money", "${pay!!.payPrice}")
                    it.withString("tradeSerialNo", pay!!.sn)
                    it.withInt("type", 3)
                })
                callback?.invoke(true)
            }
        }

    }

    /**
     * 跳转到武时亿支付主页面
     * @param type 0/主页 1/主页中取现
     */
    fun skipAsiaPayHome(activity: SimpleActivity<*,*>, type: Int = 0) {
        getAuthorization(activity, true) { canSkip ->
            if (canSkip) {
                ARouter.getInstance().build("/pay/paycapital")
                        .navigation()
            }
        }

    }

    /**
     * 跳转到武时亿支付主页面
     * @param type 0/主页 1/主页中取现
     */
    fun skipAsiaPayHome2(activity: SimpleActivity<*,*>) {
        getAuthorization(activity, true) { canSkip ->
            if (canSkip) {
                ARouter.getInstance().build("/pay/payhome")
                        .navigation()
            }
        }

    }

    /**
     * 跳转到武时亿支付交易记录
     */
    fun skipAsiaPayBill(activity: SimpleActivity<*,*>) {
        getAuthorization(activity, true) { canSkip ->
            if (canSkip) {
                ARouter.getInstance().build("/pay/paybill")
                        .navigation()
            }
        }
    }

    /**
     * 查询订单付款状态
     */
    fun checkOrderPayState(orderSn: String, callback: (isPaySuccess: Boolean) -> Unit): Disposable {
        val orderApi = ApiManager.API_ORDER

        return Observable.intervalRange(0, 3, 0, 2, TimeUnit.SECONDS)
                .flatMap {
                    orderApi.getOrderDetail(orderSn)
                }
                .flatMap {
                    if (TextUtils.equals(it.pay_status, "PAY_YES")) {
                        return@flatMap Observable.error<CustomThrowable>(CustomThrowable("PAY_YES"))
                    }
                    return@flatMap Observable.just(1)
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    callback.invoke(false)
                }, Consumer {
                    if (TextUtils.equals("PAY_YES", it.message)) {
                        callback.invoke(true)
                    } else {
                        callback.invoke(false)
                    }
                    it.printStackTrace()
                })
    }
}